package dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import entity.Cost;
import util.DBUtil;

public class CostDao implements Serializable {

	public List<Cost> findAll() {
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "select *from cost " + "order by cost_id";
			Statement state = conn.createStatement();
			ResultSet rs = state.executeQuery(sql);
			List<Cost> list = new ArrayList<Cost>();
			while (rs.next()) {
				Cost c = new Cost();
				c.setCostId(rs.getInt("cost_id"));
				c.setName(rs.getString("name"));
				c.setBaseDuration(rs.getInt("base_duration"));
				c.setBaseCost(rs.getDouble("base_cost"));
				c.setUnitCost(rs.getDouble("unit_cost"));

				c.setStatus(rs.getString("status"));
				c.setDescr(rs.getString("descr"));
				c.setCreatime(rs.getTimestamp("creatime"));
				c.setStartime(rs.getTimestamp("startime"));
				c.setCostType(rs.getString("cost_type"));

				list.add(c);

			}

			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查询资费失败", e);
		} finally {
			DBUtil.close(conn);
		}
	}

	
	public Cost findById(Integer costId) {
		Cost c = new Cost();
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "select*from cost " +
							"where cost_id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, costId);
			ResultSet rs = ps.executeQuery();
			rs.next();
			String name = rs.getString("name");
			Integer baseDuration = rs.getInt("base_duration");
			Double baseCost = rs.getDouble("base_cost");
			Double unitCost = rs.getDouble("unit_cost");
			String descr = rs.getString("descr");
			String costType = rs.getString("cost_type");

			c.setName(name);
			c.setBaseDuration(baseDuration);
			c.setBaseCost(baseCost);
			c.setUnitCost(unitCost);
			c.setDescr(descr);
			c.setCostType(costType);
			c.setCostId(costId);

			return c;
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("通过ID查询失败", e);
		} finally {
			DBUtil.close(conn);
		}
	}
	
	
	public static void main(String[] args) {

		CostDao dao = new CostDao();

		Cost cc = dao.findById(101);
		
		System.out.println(cc.getName()+","+cc.getCostType()+","+cc.getCostId());
		
	}

	

}
